package com.baor.service.impl;

import com.baor.dao.*;
import com.baor.domain.*;
import com.baor.service.AddTrashService;
import com.baor.util.R;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AddTrashServiceImpl implements AddTrashService {

    @Autowired
    private AddTrashDao addTrashDao;

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private Equipment_alertDao equipmentAlertDao;

    @Autowired
    private EquipmentDao equipmentDao;

    @Autowired
    private DeviceSalesRentalRewardConfigDao deviceSalesRentalRewardConfigDao;


    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R addTrash(Map<String, Object> params) {
        // 1. 验证必要参数
        if (!params.containsKey("code") || params.get("code") == null) {
            return R.er("设备编码不能为空");
        }
        if (!params.containsKey("phone") || params.get("phone") == null) {
            return R.er("手机号不能为空");
        }
        if (!params.containsKey("weight") || params.get("weight") == null) {
            return R.er("重量不能为空");
        }
        if (!params.containsKey("reward") || params.get("reward") == null) {
            return R.er("金额不能为空");
        }


        try {

            String equipmentCode = params.get("code").toString().trim();
            Equipment equipment = equipmentDao.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Equipment>()
                            .eq(Equipment::getCode, equipmentCode)
            );

            String customerPhone = params.get("phone").toString().trim();
            CustomerVO customervo = customerDao.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CustomerVO>()
                            .eq(CustomerVO::getPhone, customerPhone)
            );


//            if (customervo != null) {
//                int i = customervo.getNums();  //投递次数
//                double j = customervo.getWeight();     //数据库的投递重量
//                double addWeight=Double.parseDouble(params.get("weight").toString()); //本次投递的重量
//                int nums=i+1;
//                double weight=j+addWeight;
//                customervo.setNums(nums);
//                customervo.setWeight(weight);
//                // 更新数据库
//                int updateResult = customerDao.updateById(customervo);
//                if (updateResult <= 0) {
//                    return R.er("更新用户投递信息失败");
//                }
//            }
            //豆包完善后
            if (customervo != null) {
                try {
                    int i = customervo.getNums();  // 投递次数
                    double j = customervo.getTotalweight();     // 数据库的投递重量
                    double addWeight = Double.parseDouble(params.get("weight").toString()); // 本次投递的重量
                    int nums = i + 1;
                    double weight = j + addWeight;

                    customervo.setNums(nums);
                    customervo.setTotalweight(weight);

                    // 更新数据库
                    int updateResult = customerDao.updateById(customervo);
                    if (updateResult <= 0) {
                        return R.er("更新用户投递信息失败");
                    }

                } catch (NumberFormatException e) {
                    return R.er("重量参数格式错误，请输入有效的数字");
                } catch (Exception e) {
                    return R.er("更新用户信息时发生错误：" + e.getMessage());
                }
            }



            if (customervo == null) {
                return R.er("未找到对应的用户信息");
            }

            if (equipment == null) {
                return R.er("未找到对应的设备信息");
            }

            // 检查设备当前是否已满仓
            if (equipment.getStorageStatus() != null && equipment.getStorageStatus() == 1) {
                return R.er("设备已达存储上限，禁止投递");
            }

            Integer customerId = customervo.getId();
            Integer equipmentId = equipment.getId();

            // 处理当前重量（BigDecimal类型）
            BigDecimal nowWeightBigDecimal = equipment.getNowWeight();
            BigDecimal currentWeight = nowWeightBigDecimal != null ? nowWeightBigDecimal : BigDecimal.ZERO;

            // 转换参数类型（将输入的重量转换为BigDecimal）
            String phone = params.get("phone").toString().trim();
            BigDecimal weight = new BigDecimal(params.get("weight").toString());
            double reward = Double.parseDouble(params.get("reward").toString());

            // 计算新重量
            BigDecimal finalWeight = currentWeight.add(weight);

            // 检查是否超过阈值
            BigDecimal threshold = equipment.getThreshold();
//            if (threshold != null && finalWeight.compareTo(threshold) > 0) {
//                return R.er("投递后将超过设备存储阈值，关闭设备，联系清运人员");
//            }

            // 计算总重量
            BigDecimal totalWeight = equipment.getTotalWeight() != null ? equipment.getTotalWeight() : BigDecimal.ZERO;
            totalWeight = totalWeight.add(weight);

            int integral = (int) (reward * 100);

            // 更新设备信息
            equipment.setNowWeight(finalWeight);
            equipment.setTotalWeight(totalWeight);

            // 检查是否达到阈值，更新仓储状态
            if (threshold != null && finalWeight.compareTo(threshold) >= 0) {
                equipment.setStorageStatus(1); // 设置为满仓状态
                Equipment_alert alert = new Equipment_alert();

                alert.setEquipmentId(equipment.getId());
                alert.setAlertStatus(1); // 满仓状态
                alert.setAlertType("满仓预警");
                alert.setAlertDescription(equipment.getCode() + "设备即将满仓，请及时清运,地点:"+equipment.getAddress());
                alert.setAlertTime(String.valueOf(LocalDateTime.now()));
                alert.setIsDeleted(0);
                int rows =equipmentAlertDao.insert(alert);
                if (rows > 0) {
                    return R.ok("预警添加成功");
                } else {
                    return R.er("预警添加失败");
                }

            }
            equipmentDao.updateById(equipment);

            // 构建投递记录对象
            DeliveryRecordVO deliveryRecord = new DeliveryRecordVO();
            deliveryRecord.setEquipmentId(equipmentId);
            deliveryRecord.setUserId(customerId);
            deliveryRecord.setInitialWeight(currentWeight.doubleValue());
            deliveryRecord.setFinalWeight(finalWeight.doubleValue());
            deliveryRecord.setIntegral(integral);
            deliveryRecord.setPhone(phone);
            deliveryRecord.setWeight(weight.doubleValue());
            deliveryRecord.setReward(reward);
            deliveryRecord.setDeliveryTime(LocalDateTime.now().format(DATE_FORMATTER));
            deliveryRecord.setDeviceStatue(0); // 设备状态：正常
            deliveryRecord.setClearingStatus(0); // 清运状态：待反馈

            // 插入投递记录
            int rows = addTrashDao.insert(deliveryRecord);
            if (rows > 0) {
                return R.ok("投递添加成功");
            } else {
                return R.er("投递添加失败");
            }

        } catch (NumberFormatException e) {
            return R.er("重量或金额格式错误，请输入有效的数字");
        }
    }

    @Override
    public R Unitprice(Map<String, Object> params) {
        MPJLambdaWrapper<DeviceSalesRentalRewardConfig> wrapper = new MPJLambdaWrapper<>(DeviceSalesRentalRewardConfig.class)
                .select(DeviceSalesRentalRewardConfig::getRecoveryPrice);
        DeviceSalesRentalRewardConfig config = deviceSalesRentalRewardConfigDao.selectOne(wrapper);
        if (config != null) {
            // 将回收价格放入返回结果
            return R.ok(config.getRecoveryPrice());
        } else {
            // 未查询到配置时返回默认提示或值
            return R.er("未配置回收单价");
        }
    }

    @Override
    public R cabinetCode(Map<String, Object> params) {
        MPJLambdaWrapper<Equipment> wrapper = new MPJLambdaWrapper<>(Equipment.class);
        wrapper.select(Equipment::getId,
                Equipment::getCode,
                Equipment::getStatus,
                Equipment::getStorageStatus
                );
        List<Map<String, Object>> records = equipmentDao.selectJoinMaps(wrapper);
        List<Map<String, Object>> resultList = records.stream()
                .map(this::convertToFrontendFormat3)
                .collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("list", resultList);
        result.put("totalSize", resultList.size()); // 总条数为查询结果数

        return R.ok(result);
    }
    private Map<String, Object> convertToFrontendFormat3(Map<String, Object> record) {
        Map<String, Object> item = new HashMap<>();
        item.put("id", record.get("id"));
        item.put("code", record.get("code"));
        item.put("status", record.get("status"));
        item.put("storage_status", record.get("storage_status"));
        return item;
    }
}